import {
  createFilterWrapper,
  debounceFilter,
  type FunctionArgs,
  type MaybeComputedRef,
  type DebounceFilterOptions,
} from '@vueuse/core';
import { ref, unref } from 'vue';

/**
 * @description 自定义节流函数(添加是否立刻触发回调)
 * @date 28/03/2023
 * @export
 * @template T
 * @param {T} fn
 * @param {MaybeComputedRef<number>} [ms=200]
 * @param {({ immediate: boolean } & DebounceFilterOptions)} [options={ immediate: true }] immediate 是否立刻触发回调
 */
export function useDebounceFn<T extends FunctionArgs>(
  fn: T,
  ms: MaybeComputedRef<number> = 200,
  options: { immediate: boolean } & DebounceFilterOptions = { immediate: true },
) {
  const callNow = ref(false)
  if (options.immediate) {
    const deFn = createFilterWrapper(debounceFilter(ms, options), () => (callNow.value = false));
    return () => {
      deFn();
      if (!unref(callNow)) {
        callNow.value = true;
        fn?.();
      }
    };
  } else {
    return createFilterWrapper(debounceFilter(ms, options), fn);
  }
}